﻿Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging

Public Class ImageRotateHelper


    Shared Function RotateImage(ByVal b As Image, ByVal angle As Integer) As Image
        angle = angle Mod 360

        ' 弧度
        Dim radian As Double = angle * Math.PI / 180
        Dim cos = Math.Cos(radian)
        Dim sin = Math.Sin(radian)
        ' 原图的宽带和高度
        Dim w As Integer = b.Width
        Dim h As Integer = b.Height
        ' 新图的宽度和高度
        Dim WN As Integer = (Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)))
        Dim HN As Integer = (Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)))

        '' 目标位图
        Dim dsImage = New Bitmap(WN, HN)
        Dim g As Graphics = Graphics.FromImage(dsImage)
        g.InterpolationMode = InterpolationMode.HighQualityBicubic
        g.SmoothingMode = SmoothingMode.HighSpeed

        '' 便宜量
        Dim offset As Point = New Point((WN - w) / 2, (HN - h) / 2)

        '' 构造图像显示区域： 让图像的中心与窗口的中心点一致
        Dim rect As Rectangle = New Rectangle(offset.X, offset.Y, w, h)
        Dim center As Point = New Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2)


        g.TranslateTransform(center.X, center.Y)
        g.RotateTransform(360 - angle)

        '' 恢复图像在水平和垂直方向的平移
        g.TranslateTransform(-center.X, -center.Y)
        g.DrawImage(b, rect)

        '' 重置绘图的所有变换
        g.ResetTransform()
        g.Save()
        g.Dispose()

        b.Dispose()

        Return dsImage
    End Function

End Class
